package com.zenithmind.article.pojo.domain;

import com.zenithmind.common.base.BaseEntity;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;

import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Size;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.Max;
import java.util.ArrayList;
import java.util.List;

/**
 * 文章分类聚合根
 * 遵循单一职责原则：专注于分类层级管理
 * 遵循封装原则：通过方法控制层级关系
 * 遵循开闭原则：支持动态层级扩展
 */
@EqualsAndHashCode(callSuper = true)
@Getter
@NoArgsConstructor
@Schema(name = "分类实体", description = "文章分类聚合根")
public class Category extends BaseEntity {

    @NotBlank(message = "分类名称不能为空")
    @Size(max = 50, message = "分类名称长度不能超过50个字符")
    @Schema(description = "分类名称")
    private String name;

    @Size(max = 200, message = "分类描述长度不能超过200个字符")
    @Schema(description = "分类描述")
    private String description;

    @Schema(description = "父分类ID")
    private String parentId;

    @Min(value = 1, message = "层级不能小于1")
    @Max(value = 5, message = "层级不能超过5")
    @Schema(description = "层级")
    private Integer level;

    @Min(value = 0, message = "排序值不能为负数")
    @Schema(description = "排序")
    private Integer sort;

    @Schema(description = "分类状态")
    private CategoryStatus status = CategoryStatus.ACTIVE;

    @Schema(description = "文章数量")
    private Integer articleCount = 0;

    /**
     * 分类状态枚举
     */
    public enum CategoryStatus {
        ACTIVE(1, "启用"),
        DISABLED(0, "禁用");

        private final Integer code;
        private final String description;

        CategoryStatus(Integer code, String description) {
            this.code = code;
            this.description = description;
        }

        public Integer getCode() {
            return code;
        }

        public String getDescription() {
            return description;
        }

        public static CategoryStatus fromCode(Integer code) {
            if (code == null) return ACTIVE;
            for (CategoryStatus status : values()) {
                if (status.code.equals(code)) {
                    return status;
                }
            }
            return ACTIVE;
        }
    }

    // === 构造方法 ===

    /**
     * 创建根分类
     */
    public Category(String name, String description) {
        this.name = name;
        this.description = description;
        this.parentId = null;
        this.level = 1;
        this.sort = 0;
        this.status = CategoryStatus.ACTIVE;
        this.articleCount = 0;
    }

    /**
     * 创建子分类
     */
    public Category(String name, String description, String parentId, Integer parentLevel) {
        this.name = name;
        this.description = description;
        this.parentId = parentId;
        this.level = parentLevel + 1;
        this.sort = 0;
        this.status = CategoryStatus.ACTIVE;
        this.articleCount = 0;

        if (this.level > 5) {
            throw new IllegalArgumentException("分类层级不能超过5级");
        }
    }

    // === 业务方法 ===

    /**
     * 检查是否为根分类
     */
    public boolean isRoot() {
        return this.parentId == null || this.parentId.isEmpty();
    }

    /**
     * 检查是否为叶子分类（可以包含文章）
     */
    public boolean isLeaf() {
        return this.level >= 3; // 假设3级及以下为叶子分类
    }

    /**
     * 启用分类
     */
    public void enable() {
        this.status = CategoryStatus.ACTIVE;
    }

    /**
     * 禁用分类
     */
    public void disable() {
        if (this.articleCount > 0) {
            throw new IllegalStateException("包含文章的分类不能禁用");
        }
        this.status = CategoryStatus.DISABLED;
    }

    /**
     * 更新分类信息
     */
    public void updateInfo(String name, String description) {
        this.name = name;
        this.description = description;
    }

    /**
     * 设置排序
     */
    public void setSort(Integer sort) {
        if (sort < 0) {
            throw new IllegalArgumentException("排序值不能为负数");
        }
        this.sort = sort;
    }

    /**
     * 移动到新的父分类
     */
    public void moveTo(String newParentId, Integer newParentLevel) {
        if (newParentLevel != null && newParentLevel + 1 > 5) {
            throw new IllegalArgumentException("移动后的层级不能超过5级");
        }

        this.parentId = newParentId;
        this.level = newParentLevel == null ? 1 : newParentLevel + 1;
    }

    /**
     * 增加文章数量
     */
    public void incrementArticleCount() {
        this.articleCount++;
    }

    /**
     * 减少文章数量
     */
    public void decrementArticleCount() {
        if (this.articleCount > 0) {
            this.articleCount--;
        }
    }

    /**
     * 检查分类是否可用
     */
    public boolean isActive() {
        return this.status == CategoryStatus.ACTIVE;
    }

    /**
     * 检查是否可以添加文章
     */
    public boolean canAddArticle() {
        return this.isActive() && this.isLeaf();
    }

    /**
     * 获取状态码（用于数据库存储）
     */
    public Integer getStatusCode() {
        return this.status.getCode();
    }

    /**
     * 设置状态（用于数据库读取）
     */
    public void setStatusCode(Integer statusCode) {
        this.status = CategoryStatus.fromCode(statusCode);
    }

    /**
     * 生成分类路径
     */
    public String generatePath(List<Category> parentCategories) {
        if (parentCategories == null || parentCategories.isEmpty()) {
            return this.name;
        }

        StringBuilder path = new StringBuilder();
        for (Category parent : parentCategories) {
            path.append(parent.getName()).append(" > ");
        }
        path.append(this.name);
        return path.toString();
    }
}
